<template>
    <!--
	规格弹窗 说明 此组件为规格展示与交互组件，用于快速下单商品多规格显示，商品详情页面规格显示
      props：
        data      ———— 商品信息
        pageType  ———— 页面类型(quickPlaceOrder,detail)
      method：
        closePopup  ———— 关闭弹窗
        addCart     ———— 加购物车
        buyNow      ———— 直接购买
   -->
    <view class="popup-content paddingBottomBar">
        <uni-icons class="icon-close" size="48" type="closeempty" @click="closePopup"></uni-icons>
        <scroll-view class="popup-content" scroll-y="true">
            <view class="">
                <view class="sku-top">
                    <easy-pro-img customSize="200" :url="easyGetImgUrl(changeData.ThumbnailUrl310)"></easy-pro-img>

                    <view class="product-detail">
                        <view class="product-info-title">
                            <view class="product-info-title-text">{{ changeData.ProductName }}</view>
                        </view>
                        <view class="price-box">
                            <text class="price-text">￥</text>
                            <text class="price-text" v-show="changeData.CurrentMinPrice < changeData.CurrentMaxPrice">{{
                                changeData.CurrentMinPrice }}~</text>
                            <text class="price-text">{{ changeData.CurrentMaxPrice }}</text>
                            <text class="">/</text>
                            <text v-if="changeData.CurrentUnit">{{ changeData.CurrentUnit.split("=")[0] }}</text>
                        </view>
                        <view class="other">
                            <text>商品编码 {{ changeData.ProductCode }}</text>
                            <text>库存 {{ changeData.V_StockSum }}{{ changeData.DefaultUnit }}</text>
                            <text v-show="changeData.MinNum && changeData.MinNum > 0">起批 {{ changeData.MinNum }}{{
                                changeData.DefaultUnit }}</text>
                            <text v-show="LimitBuy && LimitBuy > 0">限购{{ LimitBuy }}{{ changeData.DefaultUnit }}</text>
                        </view>
                    </view>
                </view>
                <view class="sku-unit">
                    <view class="sku-unit-header">
                        <view class="unit-title">
                            <text>单位</text><text>：{{ changeData.CurrentUnit }}</text>
                        </view>
                        <view v-if="changeData.ProductSkuList && changeData.ProductSkuList.length > 1 && false"
                            class="batch-check-box" @click="isBatch = !isBatch">
                            <text class="batch-text">批量加购</text>
                            <view class="select-box" :class="isBatch ? 'selected' : ''">
                                <uni-icons v-if="isBatch" type="checkmarkempty" size="26" customIcons="icon-yellow">
                                </uni-icons>
                            </view>
                        </view>
                    </view>
                    <view v-if="changeData.ProductUnitList && changeData.ProductUnitList.length > 0" class="unit-items">
                        <view v-for="(item, index) in changeData.ProductUnitList" :key="index" class="btn btn-gray-fill"
                            :class="changeData.UnitActiveIndex == index ? 'btn-success-fill' : ''"
                            v-if="index > customizationShow" @click="changeUnit(index)">
                            {{ item.UnitName }}
                            <uni-badge v-if="isBatch" class="badge" size="small" :text="getBadgeNumForBatch(item)"
                                absolute="rightTop" type="error" :offset="[-50, -40]"></uni-badge>
                            <uni-badge v-else class="badge" size="small" :text="getBadgeNum(item)" absolute="rightTop"
                                type="error" :offset="[-50, -40]"></uni-badge>
                        </view>
                    </view>
                </view>

                <!-- 规格 -->
                <view v-for="(item, index) in changeData.ProductUnitList"
                    v-show="changeData.UnitActiveIndex === index && !isBatch" :key="index">
                    <view v-if="item.ProductSkuAttrList && item.ProductSkuAttrList.length > 0">
                        <specTree :min-num="changeData.MinNum" :limit-buy="changeData.LimitBuy"
                            :tree-data="item.ProductSkuAttrList" :data="changeData" :active-index="activeIndex"
                            :active-id="activeId" @setCarListFunc="setCarListFunc"
                            :unitActiveIndex="changeData.UnitActiveIndex" @inquire="inquire" :selectType="selectType"
                            @treeClickEvent="treeClickEvent" :tempType="tempType" :addNum="changeData.AddNum" />
                    </view>
                </view>

                <!-- 批量规格 -->
                <view v-for="(batchItem, numBoxIndex) in batchInfo"
                    v-if="changeData.UnitActiveIndex === numBoxIndex && isBatch" class="sku-unit"
                    :key="batchItem.UnitId">
                    <view>
                        <view v-for="(item, index) in batchItem.selectItems" :key="index" class="">
                            <view class="">{{ item.AttributeName }}：</view>
                            <view v-show="item.items && item.items.length > 0" class="unit-items">
                                <view v-for="(ite, inde) in item.items" :key="inde" class="btn btn-gray-fill"
                                    :class="ite.Selected ? 'btn-success-fill' : ''"
                                    @click="chooseSpec(item, index, ite, inde, batchItem)">
                                    {{ ite.ValueStr }}
                                </view>
                            </view>
                        </view>
                        <view class="batch-num-box">
                            <text class="num-title">数量</text>
                            <view class="input-number-box">
                                <button class="btn-minus num-btn" :class="batchItem.Amount <= 0 ? 'color-shadow' : ''"
                                    @click="changeAmount(batchItem.Amount, -1, batchItem)"
                                    :disabled="isDisable(batchItem)">
                                    -
                                </button>
                                <view class="btn-input-box">
                                    <input v-model="batchItem.Amount" maxlength="6" type="number" class="btn-input"
                                        @blur="changeAmount(batchItem.Amount, 0, batchItem)"
                                        :disabled="isDisable(batchItem)" />
                                </view>
                                <button class="btn-plus num-btn" @click="changeAmount(batchItem.Amount, 1, batchItem)"
                                    :disabled="isDisable(batchItem)">
                                    +
                                </button>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>
        <view class="bottom-bar no-shadow" v-if="!isBatch">
            <view class="btn btn-success btn-fill btn-addCart" @click="addCart" v-if="selectType == 4">加入清单</view>
            <view class="btn btn-success btn-fill btn-addCart" @click="addCart" v-else>加入购物车</view>
        </view>
        <view class="bottom-bar no-shadow" v-else>
            <cover-view class="btn btn-fill btn-yellow-hollow btn-addCart" @click="addCartBatch(1)">
                <cover-view>一键添加</cover-view>
            </cover-view>
            <cover-view class="btn btn-success btn-fill btn-addCart btn-next" @click="addCartBatch(2)">
                <cover-view>下一步</cover-view>
            </cover-view>
        </view>
    </view>
</template>

<script>
import specTree from "@/components/product/spec-tree.vue"
import easyProImg from "@/components/easy/easy-pro-image.vue"
import { updateCart } from "@/utils/cartUtil.js"
import { upTempCartFn } from "@/utils/tempCartUtil.js"
import { upValetCartFn } from "@/utils/valetCartUtil.js"
import { setReduce } from "@/utils/utils.js"
import storage from "@/uni-sub-base/utils/storage.js"
export default {
    name: "ProductSpec",
    components: {
        specTree,
        easyProImg,
    },
    props: {
        data: {
            // 数据
            type: Object,
            required: true,
        },
        fresh: {
            type: Boolean,
            required: false,
            default: false,
        },
        pageType: {
            // 按钮类型
            type: String,
            required: false,
            default: "quickPlaceOrder",
        },
        tempType: {
            type: Number,
            default: 0,
        },
        valetUserId: {
            type: Number,
            default: 0,
        },
        warehouseId: {
            type: Number,
            default: 0,
        },
        isGift: {
            type: String,
            default: "",
        },
        selectType: {
            type: [Number, String],
            default: 0,
        }
    },
    data() {
        return {
            changeData: {},
            activeUnitIndex: -1,
            activeUnitName: "",
            activeUnitRatio: 1,
            activeSpecIndex: -1,
            secondSpecList: [],
            cartRequestObj: [],
            ProductSkuAttrList: [],
            V_GradePrice: "",
            LimitBuy: 0,
            // guige
            activeIndex: 0,
            activeId: 0,
            classifyList: [],
            //是否是单规格
            isSingle: false,
            // 批量加购
            isBatch: false,
            batchData: [],
            batchInfo: [],
            cartBatchRequestList: [],
            allSkuModel: [],
            customizationShow: -1, // 是否显示单位  多单位默认选第二,单个选第一
        }
    },
    watch: {
        data(newVal, oldVal) {
            this.init()
        },
        fresh(newVal, oldVal) {
            this.init()
        },
        cartRequestList(e) { },
    },
    created() {
        this.init()
    },
    methods: {
        inquire(item) {
            this.$emit("inquire", item)
        },
        isDisable(data) {
            let isDisable = true
            let allArr = []
            data.selectItems.forEach((item) => {
                let isPass = 0
                item.items.forEach((e) => {
                    if (e.Selected) {
                        isPass = 1
                    }
                })
                allArr.push(isPass)
            })
            return allArr.includes(0)
        },
        //获取批量加购角标
        getBadgeNumForBatch(item) {
            let current = item.UnitName
            let num = 0
            this.batchInfo.forEach((e) => {
                if (current == e.UnitName) {
                    num += e.Amount
                }
            })
            if (num > 0) {
                num = num.toFixed(2)
            }
            return Number(num)
        },
        //获取角标
        getBadgeNum(item) {
            let current = item.UnitName
            let num = 0
            this.cartRequestList.forEach((e) => {
                if (current == e.UnitName) {
                    num += e.Amount
                }
            })
            if (num > 0) {
                num = num.toFixed(2)
            }
            return Number(num)
        },
        treeClickEvent(item, treeItem) {
            console.log(item)
        },
        // 遍历规格添加数据
        initLoopArr(arr, betchOjb = null, lv = 0) {
            if (arr && arr.length > 0) {
                let obj = {
                    lv,
                    AttributeName: arr[0].AttributeName,
                    items: [],
                }
                lv = lv + 1
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i].ProductAttrList && arr[i].ProductAttrList.length > 0) {
                        //有子项
                        if (betchOjb) {
                            arr[i].Selected = false
                            obj.items.push(arr[i])
                            this.initLoopArr(arr[i].ProductAttrList, betchOjb, lv)
                        } else {
                            this.initLoopArr(arr[i].ProductAttrList)
                        }
                    } else {
                        //没有子项
                        if (arr[i].SkuModel && arr[i].SkuModel.ProductUnitPrice) {
                            const _SkuModel = arr[i].SkuModel
                            const _ProductUnitPrice = arr[i].SkuModel.ProductUnitPrice
                            arr[i].Stock = _SkuModel.Stock
                            arr[i].AddNum = _SkuModel.AddNum
                            arr[i].ProductId = _ProductUnitPrice.ProductId
                            arr[i].Amount = _ProductUnitPrice.Amount || 0
                            arr[i].Ratio = _ProductUnitPrice.Ratio
                            arr[i].SkuId = _ProductUnitPrice.SkuId
                            arr[i].UnitId = _ProductUnitPrice.UnitId
                            arr[i].UnitName = _ProductUnitPrice.UnitName
                            arr[i].V_AttributeNameValue = _SkuModel.AttributeNameValue
                            arr[i].V_FactPrice = _SkuModel.ProductUnitPrice.Price
                            arr[i].Selected = false
                            if (betchOjb) {
                                obj.items.push(arr[i])
                                this.allSkuModel.push(arr[i])
                            }
                        }
                    }
                }
                betchOjb.selectItems.unshift(obj)
            } else {
                console.log("arr不是数组，不能遍历")
            }
        },
        init() {
            const _this = this
            this.activeUnitIndex = -1
            this.activeUnitName = ""
            this.activeUnitRatio = 1
            this.activeSpecIndex = -1
            this.secondSpecList = []
            this.cartRequestList = []

            this.batchData = []
            this.changeData = this.data
            if (this.data.ProductAttributesList) {
                this.ProductAttributesList = JSON.parse(JSON.stringify(this.data.ProductAttributesList))
                this.batchData.length = this.ProductAttributesList.length
            }
            //获取所有属性
            // 初始化批量加购设置
            this.isBatch = false
            this.batchInfo = []
            if (this.changeData.ProductUnitList && this.changeData.ProductUnitList.length > 0) {
                this.changeData.ProductUnitList.forEach((item) => {
                    if (item.ProductSkuAttrList && item.ProductSkuAttrList.length > 0) {
                        let betchOjb = {
                            Amount: 0,
                            UnitId: item.UnitId,
                            UnitName: item.UnitName,
                            selectItems: [],
                        }
                        _this.initLoopArr(item.ProductSkuAttrList, betchOjb, 0)
                        this.batchInfo.push(betchOjb)

                        //去重 去掉相同级别的选项
                        this.batchInfo.forEach((e) => {
                            e.selectItems = setReduce(e.selectItems, "lv")
                        })
                    }
                })
            }

            this.V_GradePrice = this.changeData.V_GradePrice
            this.LimitBuy = this.changeData.LimitBuy
            if (this.changeData.UnitList && this.changeData.UnitList.length > 0) {
                this.changeData.UnitList.forEach((item, index) => {
                    if (this.changeData.DefaultUnit === item) {
                        this.activeUnitIndex = index
                        this.activeUnitName = this.changeData.UnitList[index]
                        this.activeUnitRatio = this.changeData.UnitratioList[index]
                    }
                })
            } else {
                this.activeUnitName = this.changeData.BaseUnit
            }
            // 单位默认
            if (this.changeData.ProductUnitList && this.changeData.ProductUnitList.length > 1) {
                this.changeData.ProductUnitList.forEach((item, index) => {
                    if (item.IsCustomized) {
                        this.customizationShow = 0
                        this.changeUnit(1) //默认选第二个
                    } else {
                        this.changeUnit(0) //默认选第二个
                    }
                })
            } else {
                this.changeUnit(0) //默认选第一个
            }
        },
        // 关闭弹窗
        closePopup() {
            this.$emit("closePopup")
        },
        // 批量方法
        changeAmount(num, addnum, batchItem) {
            batchItem.Amount = Number(num) + Number(addnum) >= 0 ? Number(num) + Number(addnum) : 0
            this.$forceUpdate()
        },
        chooseSpec(item, index, ite, inde, batchItem) {
            ite.Selected = !ite.Selected
            this.$forceUpdate()
        },
        // 加入购物车
        addCart() {
            console.log(this.tempType)

            if (this.cartRequestList && this.cartRequestList.length > 0) {
                if (this.tempType == 0) {
                    updateCart(this.cartRequestList).then((res) => { })
                } else if (this.tempType == 1) {
                    this.cartRequestList.forEach((item) => {
                        upTempCartFn(item).then((res) => {
                            this.$forceUpdate()
                        })
                    })
                } else if (this.tempType == 2) {
                    this.cartRequestList.forEach((item) => {
                        let param = {
                            amount: item.Amount,
                            productId: item.ProductId,
                            ratio: item.Ratio,
                            ratioUnit: item.UnitName,
                            skuId: item.SkuId,
                            valetUserId: this.valetUserId,
                            warehouseId: this.warehouseId,
                            isGift: this.isGift ? true : false,
                        }
                        upValetCartFn(param).then((res) => {
                            this.$forceUpdate()
                        })
                    })
                }
            }
            this.$emit("addCart", this.cartRequestList)
        },
        // 批量加入购物车
        addCartBatch(type) {
            let arr = []
            this.allSkuModel = this.allSkuModel.filter((item) => {
                return item.Stock > 0
            })
            this.batchInfo.forEach((unitItem) => {
                if (unitItem.Amount > 0) {
                    let skus = this.allSkuModel.filter((item) => {
                        return item.UnitId == unitItem.UnitId
                    })
                    unitItem.selectItems.forEach((e) => {
                        let getArr = []
                        e.items.forEach((sub) => {
                            if (sub.Selected) {
                                let name = sub.AttributeName + "_" + sub.ValueStr
                                let result = skus.filter((item) => {
                                    return item.SkuModel.AttributeNameValue.includes(name)
                                })

                                getArr = getArr.concat(result)
                            }
                        })
                        skus = getArr
                    })
                    skus.forEach((sku, index) => {
                        console.log(sku)
                        let skuStock = sku.Stock
                        sku.Amount = unitItem.Amount > skuStock ? skuStock : unitItem.Amount
                    })
                    arr = arr.concat(skus)
                }
            })
            //没有数据不处理
            if (arr.length < 1) {
                this.easyToast("未选择或所选商品都无库存")
                return
            }
            if (type == 1) {
                //加入购物车
                updateCart(arr, true).then((res) => { })
                this.$emit("addCart", arr)
            } else {
                //下一步
                let obj = {
                    data: this.changeData,
                    arr: arr,
                }
                storage.setCache("tempCart", obj)
                this.easyGoTo("/pages/product/selectSpec")
            }
        },
        //切换单位
        changeUnit(index) {
            this.changeData.UnitActiveIndex = index
            this.changeData.CurrentUnit = this.changeData.ProductUnitList[index].UnitName
            this.changeData.CurrentUnitId = this.changeData.ProductUnitList[index].UnitId
            let min = 0
            let max = 0
            this.changeData.ProductUnitList[index].SkuUnitPriceList.forEach((e, index) => {
                let price = e.Price
                if (index == 0) {
                    min = price
                    max = price
                } else {
                    if (price < min) {
                        min = price
                    }
                    if (price > max) {
                        max = price
                    }
                }
            })

            this.changeData.CurrentMaxPrice = max
            this.changeData.CurrentMinPrice = min
            // this.changeData.CurrentMaxPrice = this.changeData.SaleMaxPrice * this.changeData.ProductUnitList[index]
            // 	.Ratio
            // this.changeData.CurrentMinPrice = this.changeData.SaleMinPrice * this.changeData.ProductUnitList[index]
            // 	.Ratio

            this.$forceUpdate()
            this.$emit("changeUnit", this.changeData)
        },
        setCarListFunc(obj) {
            //商品购物车
            let _newObj = true
            if (this.cartRequestList && this.cartRequestList.length > 0) {
                for (let i = 0; i < this.cartRequestList.length; i++) {
                    if (
                        obj.UnitId === this.cartRequestList[i].UnitId &&
                        obj.SkuId === this.cartRequestList[i].SkuId &&
                        obj.ProductId === this.cartRequestList[i].ProductId
                    ) {
                        this.cartRequestList[i].Amount = obj.Amount
                        _newObj = false
                        break
                    }
                }
            }
            if (_newObj) {
                this.cartRequestList.push(obj)
            }
            this.$forceUpdate()
        },
    },
}
</script>

<style lang="scss" scoped>
.pop-main-box {
    display: flex;
    position: relative;
    background: $color-white;
    border-radius: 40rpx 40rpx 0 0;
    padding-top: 20rpx;
    max-height: 60vh;
}

.icon-close {
    position: fixed;
    top: $app-page-padding;
    right: $app-page-padding;
    z-index: 1;
}

// 弹窗组件
.popup-content {
    display: flex;
    position: relative;
    background: $color-white;
    border-radius: 40rpx 40rpx 0 0;
    padding-top: 20rpx;
    max-height: 80vh;
    z-index: 0;

    .sku-top {
        display: flex;
        flex-direction: row;
        padding: $app-page-padding;

        .product-img {
            width: 200rpx;
            height: 200rpx;
            margin-right: 20rpx;
        }

        .product-detail {
            display: flex;
            flex: 1;
            flex-direction: column;

            .price-box {
                display: flex;
                flex: 1;
                align-items: center;
            }

            .other {
                display: flex;
                flex-direction: column;

                text {
                    margin-top: 20rpx;
                }
            }

            .price-text {
                font-size: $font-size-36;
                color: $color-orange-1;
                font-weight: 600;
            }
        }
    }

    .sku-unit {
        padding: $app-page-padding;

        .sku-unit-header {
            display: flex;
            flex-direction: row;

            .unit-title {
                flex: 1;
            }

            .batch-check-box {
                display: flex;
                flex-direction: row;
                align-items: center;

                .batch-text {
                    margin-right: 10rpx;
                }

                .select-box {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    width: 24rpx;
                    height: 24rpx;
                    border: solid 1rpx $app-color-text-tip;
                    border-radius: 4rpx;
                }

                .selected {
                    border-color: $color-yellow-4;
                }
            }
        }

        .unit-items {
            display: flex;
            flex-direction: row;
            margin: 20rpx 0;

            .btn {
                min-width: 60rpx;
                height: 60rpx;
                border-radius: $border-radius-10;
                margin-right: 20rpx;
                font-size: 26rpx;
            }
        }
    }

    .bottom-bar {
        .btn {
            text-align: center;
            height: 90rpx;
            line-height: 90rpx;
            background: $app-color-main;
            border-radius: 44rpx;
            font-size: 32rpx;
            color: #ffffff;

            &:first-child {
                margin-left: 0;
            }
        }

        .btn-batch {
            flex: 1;
            border: solid 1rpx $color-black-1;
        }

        .btn-addCart {
            flex: 3;
        }
    }
}

.batch-num-box {
    display: flex;
    flex-direction: row;
    border-top: solid 1rpx $app-color-input-bg;
    padding-top: $app-page-padding;

    .num-title {
        display: flex;
        flex: 1;
    }

    .num-btn {
        display: flex;
        justify-content: center;
        align-items: center;

        &:after {
            border: 0 !important;
        }
    }

    .btn {
        border-radius: 100rpx;
    }
}

.btn-next {
    margin-left: $app-page-padding;
}

.bottom-bar {
    .btn-addCart {
        flex: 1;
    }
}
</style>
